import wmx from '@/common/wmx';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { createRouter, createWebHashHistory } from 'vue-router';

const routes = [
    {
        path: '/',
        name: 'login',
        component: () => import('@/pages/main/Login'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/layout',
        name: 'layout',
        component: () => import('@/pages/main/Layout'),
        meta: {
            title: '控制台'
        }
    },

    {
        path: '/error',
        name: 'error',
        component: () => import('@/pages/main/Error'),
        meta: {
            title: 'error'
        }
    }
];

const router = createRouter({
    routes,
    history: createWebHashHistory()
});

//路由守卫
var isPush = false;
NProgress.configure({ showSpinner: false });
const modules = Object.assign(import.meta.glob('../pages/**/*.vue'), import.meta.glob('../pages/**/**/*.vue'));
router.beforeEach((to, from, next) => {
    const proxy = wmx.app.config.globalProperties;
    if (to.name) {
        NProgress.start();
        document.title = to.meta.title;
        next();
    } else {
        if (isPush) {
            next({ path: '/error' });
        } else {
            //动态路由
            let store = proxy.$pinia.state.value.store;
            let menu = proxy.$tools.flatten(store.menu);
            for (let row of menu) {
                if ([1, 3, 4].includes(Number(row.type))) {
                    router.addRoute('layout', {
                        path: row.route,
                        name: row.key,
                        component: modules['../pages/' + row.component],
                        meta: {
                            title: row.name
                        }
                    });
                }
                
            }
            
            isPush = true;
            next({ ...to, replace: true });
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});

export default router;
